package com.atguigu.system.service;

import com.atguigu.common.result.ResultCodeEnum;
import com.atguigu.common.utils.BeanUtils;
import com.atguigu.model.system.SysMenu;
import com.atguigu.model.vo.menu.SysMenuQueryRespVo;
import com.atguigu.model.vo.menu.SysMenuQueryTreeRespVo;
import com.atguigu.model.vo.menu.SysMenuSaveReqVo;
import com.atguigu.model.vo.menu.SysMenuUpdateReqVo;
import com.atguigu.system.exception.GuiguException;
import com.atguigu.system.manager.SysMenuManager;
import com.atguigu.system.utils.MenuHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * SysMenuService
 * </p>
 *
 * @author flyduck
 * @since 2023/10/25
 */
@Service
public class SysMenuServiceImpl {
    @Autowired
    private SysMenuManager sysMenuManager;

    /**
     * 菜单列表（树形）
     * @return
     */
    public List<SysMenuQueryTreeRespVo> findNodes() {
        //获取所有菜单
        List<SysMenu> sysMenuList = sysMenuManager.list();
        List<SysMenuQueryTreeRespVo> sysMenuQueryTreeRespVoList = BeanUtils.toBeanList(sysMenuList, SysMenuQueryTreeRespVo.class);
        //将菜单转换成要求的格式
        List<SysMenuQueryTreeRespVo> resultList = MenuHelper.buildTree(sysMenuQueryTreeRespVoList);
        return resultList;
    }

    /**
     * 添加菜单
     * @param reqVo
     * @return
     */
    public boolean save(SysMenuSaveReqVo reqVo) {
        SysMenu sysMenu = BeanUtils.toBean(reqVo, SysMenu.class);
        return sysMenuManager.save(sysMenu);
    }

    /**
     * 根据id查询菜单
     * @param id
     * @return
     */
    public SysMenuQueryRespVo getById(Long id) {
        SysMenu sysMenu = sysMenuManager.getById(id);
        SysMenuQueryRespVo respVo = BeanUtils.toBean(sysMenu, SysMenuQueryRespVo.class);
        return respVo;
    }

    /**
     * 修改菜单
     * @param reqVo
     * @return
     */
    public boolean updateById(SysMenuUpdateReqVo reqVo) {
        SysMenu sysMenu = BeanUtils.toBean(reqVo, SysMenu.class);
        return sysMenuManager.updateById(sysMenu);
    }

    /**
     * 删除菜单
     * @param id
     * @return
     */
    public boolean removeById(Long id) {
        //查询当前菜单下面是否有菜单
        Integer count = sysMenuManager.countByParentId(id);
        if (count > 0) {
            throw new GuiguException(ResultCodeEnum.NODE_ERROR);
        }
        return sysMenuManager.removeById(id);
    }
}
